<?
/**
 * This file is part of XNAT light.
 *
 * XNAT light is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * XNAT light is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XNAT light.  If not, see <http://www.gnu.org/licenses/>.
 */
namespace NRG\Framework\Database\SQL;

use NRG\Framework\Exceptions\QueryException as QueryException;
use NRG\Framework\Common\Registry as Registry;

/**
 * MySQL database
 *
 * @package NRG\Framework\Database\SQL
 */
class Mysql
{
    /**
     * PHP database object
     *
     * @var PDO
     */
    protected $_pdo;

    /**
     * SQL query array
     *
     * @var string
     */
    protected $_query;

    /**
     * Constructor
     *
     * @param string $host mysql.localdomain
     * @param string $dbname mydb
     * @param string $username username
     * @param string $password p@$$w0rd
     */
    public function __construct($host, $dbname, $username, $password)
    {
	$this->_pdo = new \PDO("mysql:host=$host;dbname=$dbname", $username, $password);

	Registry::put("database", $this);
    }

    /**
     * Execute databse transaction
     * 
     * @param string $query
     * @param array $values
     * @return array
     * @throws QueryException
     */
    public function query($query=null, $values=array(), $transaction=true)
    {
	if($query == null)
	    throw new QueryException(QueryException::NULL_QUERY);

	try
	{
	    if($transaction)
		$this->_pdo->beginTransaction();

	    $statement = $this->_pdo->prepare($query);

	    $statement->execute($values);

	    $this->commit();
	}
	catch(\Exception $e)
	{
	    $this->rollback();
	}

	return $statement->fetchAll();
    }

    /**
     * Rollback previous transaction
     *
     * @return boolean
     */
    public function rollback()
    {
	$this->_pdo->rollback();
    }

    /**
     * Commit transaction to database
     *
     * @return boolean
     */
    public function commit()
    {
	$this->_pdo->commit();
    }
}
